//
//  QCListViewController.m
//  QCSliderTableView
//
//  Created by “ 邵鹏 on 14-4-16.
//  Copyright (c) 2014年 Scasy. All rights reserved.
//

#import "QCListViewController.h"
#import "JWTCourseTableViewCell.h"
#import "JWTListCourse.h"
#import "JWTStoreCourseDetailViewController.h"

typedef void(^CourseListBlock)(NSString *storeName);

static NSString *courseTableViewCell_Identifier = @"courseTableViewCell_Identifier";

@interface QCListViewController ()

/** current page number */
@property (nonatomic,assign) NSInteger currentPageNum;

/** one page number 30 */
@property (nonatomic,assign) NSInteger currentNumPerPage;

/** totalCounts 一共多少纪录 */
@property (nonatomic,assign) NSInteger currentTotalPageNumber;

@end

@implementation QCListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.currentPageNum = 0;
        self.currentNumPerPage = 30;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //NSLog(@"viewDidLoad title = %@",self.title);

    [self initWithTableView];
    
    WS(weakSelf);
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    _tableViewList.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf reloadData];
    }];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    _tableViewList.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf reloadDataMore];
    }];
}

-(void)setStoreID:(NSString *)storeID{
    APPDELEGATE.storeID = storeID;
    [self reloadData];
}

-(void)setCourseType:(NSString *)courseType{
    APPDELEGATE.courseType = courseType;
    [self reloadData];
}

-(void) initWithTableView{
    _tableViewList = [[UITableView alloc] initWithFrame:CGRectMake(self.view.left, self.view.top, UISCREEN_WIDTH, UISCREEN_HEIGHT-64-54)];
    _tableViewList.dataSource = self;
    _tableViewList.delegate = self;
    _tableViewList.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableViewList];
    [_tableViewList registerClass:[JWTCourseTableViewCell class] forCellReuseIdentifier:courseTableViewCell_Identifier];
}

- (void)viewDidCurrentView
{
//    NSLog(@"加载为当前视图 = %@",self.title);
    //处理2.15,星期三,2017-01-07
    NSArray *calendarArr = [self.title componentsSeparatedByString:@","];
    if (calendarArr.count > 2) {
        APPDELEGATE.startTime = calendarArr[2];
        [self reloadData];
    }

}

-(void) reloadData{
    self.currentPageNum = 1;
    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getJWTStoreListCoursePage:self.currentPageNum andPageSize:PageSize];
    [HUD showUIBlockingIndicator];
    [AFNHttpsRequest requestWithUrl:urlString WithParam:nil WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
        _tableViewList.footer.hidden = YES;
        [_tableViewList.header endRefreshing];
        [_tableViewList.footer endRefreshing];
        [HUD hideUIBlockingIndicator];
        if (model) {
            if ([[model objectForKey:@"code"]integerValue] == 200) {
                
                _listArray = [NSMutableArray arrayWithArray:[[model objectForKey:@"data"] objectForKey:@"list"]];
                
                _currentTotalPageNumber = [[[model objectForKey:@"data"] objectForKey:@"totalCount"] integerValue];
                NSLog(@"%@---%@",_listArray,[[model objectForKey:@"data"] objectForKey:@"list"]);
                
                if (_listArray.count == 0) {
                    _tableViewList.footer.hidden = YES;
                }else{
                    _tableViewList.footer.hidden = NO;
                }
                
                if (_listArray.count <= _currentTotalPageNumber) {
                    // 已经全部加载完毕
                    [_tableViewList.mj_footer endRefreshingWithNoMoreData];
                }
                
                [_tableViewList reloadData];
            }
        }
    }];
}

-(void) reloadDataMore{
        self.currentPageNum ++;
        NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getJWTStoreListCoursePage:self.currentPageNum andPageSize:PageSize];
        [HUD showUIBlockingIndicator];
        [AFNHttpsRequest requestWithUrl:urlString WithParam:nil WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
            [_tableViewList.header endRefreshing];
            [_tableViewList.footer endRefreshing];
            [HUD hideUIBlockingIndicator];
            if (model) {
                if ([[model objectForKey:@"code"]integerValue] == 200) {
                    
                    [_listArray addObject:[[model objectForKey:@"data"] objectForKey:@"list"]];
                    
                    if (_listArray.count <= self.currentTotalPageNumber) {
                        NSLog(@"%@---%@",_listArray,[[model objectForKey:@"data"] objectForKey:@"list"]);
                        [_tableViewList reloadData];
                        // 已经全部加载完毕
                        [_tableViewList.mj_footer endRefreshingWithNoMoreData];
                    }else{
                        // 已经全部加载完毕
                        [_tableViewList.mj_footer endRefreshingWithNoMoreData];
                    }
                    
                }
            }
        }];
}


#pragma mark - 表格视图数据源代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    if (_listArray.count == 0) {
        [[JWTDefaultNoDataView sharedInstance] showNoDataWithView:_tableViewList andImageName:ImageViewDefault andTitle:@"暂无可预约课程"];
    }else{
        [[JWTDefaultNoDataView sharedInstance] hideNODATAImageView:_tableViewList];
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JWTCourseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:courseTableViewCell_Identifier forIndexPath:indexPath];
    JWTListCourse *listCourse = [JWTListCourse mj_objectWithKeyValues:[_listArray objectAtIndex:indexPath.row]];
    [cell.courseImageView  sd_setImageWithURL:[[JWTAPPHttpsUrl sharedInstance]urlAppendString:listCourse.picture] placeholderImage:[UIImage imageNamed:ImageViewDefault]];
    cell.courseNameLabel.text = listCourse.coursename;
//    cell.coachNameLabel.text = [NSString stringWithFormat:@"教练:%@",listCourse.coach.name];    
    cell.coursePriceLabel.text = [NSString stringWithFormat:@"¥%ld/课",listCourse.price];;
    cell.coursePersonLabel.text = [NSString stringWithFormat:@"(%ld/%ld人)",listCourse.ordernum,listCourse.totalnum];
    
    cell.courseTimeLabel.text = [NSString stringWithFormat:@"%@~%@",listCourse.starttime == nil?@"":[listCourse.starttime substringWithRange:NSMakeRange(5, 11)],listCourse.endtime == nil?@"":[listCourse.endtime substringWithRange:NSMakeRange(5, 11)]];
    
    //
    JWTDateString *dateString = [JWTDateString sharedInstance];
    NSString *cur_date_string = [dateString stringFromDate:[NSDate date]];
    if ([dateString compareSmallerTwoDate:cur_date_string Other:listCourse.starttime] == YES) {
        cell.courseStateLabel.text = @"即将开始";
    }else if ([dateString compareSmallerTwoDate:cur_date_string Other:listCourse.endtime] == NO){
        cell.courseStateLabel.text = @"已结束";
    }else{
        cell.courseStateLabel.text = @"进行中";
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    JWTStoreCourseDetailViewController *vc = [[JWTStoreCourseDetailViewController alloc] init];
    UITabBarController *tabBar = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UINavigationController *nav = tabBar.selectedViewController;
    if (_listArray.count > 0) {
        JWTListCourse *listCourse = [JWTListCourse mj_objectWithKeyValues:[_listArray objectAtIndex:indexPath.row]];
        vc.courseID = listCourse.courseid;
        [nav pushViewController:vc animated:YES];
    }
    
//    [self presentViewController:vc animated:YES completion:nil];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    static JWTCourseTableViewCell *cell = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cell = [tableView dequeueReusableCellWithIdentifier:courseTableViewCell_Identifier];
    });
    return cell.height;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
